package c2;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeTest {
    //在getUnsafe()方法里判断是不是Bootstrap类加载器加载的localClass对象，而这里是AppClassLoader加载的，直接抛出异常
    //private static final Unsafe unsafe=Unsafe.getUnsafe();
    private static final Unsafe unsafe;
    //记录变量state在类UnsafeTest中的偏移量
    private static final long stateOffset;

    private volatile long state=0;

    static {
        try {
            //通过反射获取Unsafe的成员变量theUnsafe
            Field field=Unsafe.class.getDeclaredField("theUnsafe");
            //设置为可存取
            field.setAccessible(true);
            //获取该变量的值
            unsafe=(Unsafe) field.get(null);
            stateOffset=unsafe.objectFieldOffset(UnsafeTest.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new Error(e);
        }
    }

    public static void main(String[] args){
        UnsafeTest unsafeTest=new UnsafeTest();
        Boolean success=unsafe.compareAndSwapInt(unsafeTest,stateOffset,0,1);
        System.out.println(success);
    }

}
